//
//  MSSearchDefaultView.m
//  MSJD
//
//  Created by 箭军刘 on 2018/11/3.
//  Copyright © 2018 xiangbo. All rights reserved.
//

#import "MSSearchDefaultView.h"

#import "MSSearchDefaultCell.h"

#import "MSSearchDataSource.h"

@interface MSSearchDefaultView()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, assign) NSInteger kind;

@property (nonatomic, copy) NSArray *historyArr; // 历史搜索数组
@property (nonatomic, copy) NSArray *recommondArr; // 推荐数组

@end

@implementation MSSearchDefaultView {
    NSInteger _defaultSearchType;
}

+ (instancetype)loadSearchDefaultViewWithKind:(NSInteger)kind {
    MSSearchDefaultView *searchDefaultView = [[MSSearchDefaultView alloc] initWithFrame:CGRectZero kind:kind];
    return searchDefaultView;
}

- (instancetype)initWithFrame:(CGRect)frame kind:(NSInteger)kind {
    if (self = [super initWithFrame:frame]) {
        
        self.kind = kind;
        self.backgroundColor = [UIColor clearColor];
        _defaultSearchType = 0;
        [self initSubViews];
        [self loadData];
    }
    return self;
}

#pragma mark - Init Method

- (void)initSubViews {
    // 添加tableView
    [self addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.offset(0);
    }];
}

- (void)loadData {
    [self loadLocalHistoryData];
    [self loadSearchRecommondData];
}
/** 加载本地历史数组 */
- (void)loadLocalHistoryData {
    NSArray *localSearchList = [MSSearchDataSource searchHistoryList];
    if (localSearchList.count > 0) {
        if (self.historyArr.count > 0) {
            // 当前已有历史数据，现在也有，就直接刷新
            self.historyArr = localSearchList;
            _defaultSearchType = 0;
            // 刷新第一组数据
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
        } else {
            // 当前已有历史数据，之前没有，直接刷新全部
            self.historyArr = localSearchList;
            _defaultSearchType = 0;
            [self.tableView reloadData];
        }
    } else {
        _defaultSearchType = 1;
        self.historyArr = [NSArray array];
        [self.tableView reloadData];
    }
}
/** 加载搜索推荐数据 */
- (void)loadSearchRecommondData {
    _WEAKSELF
    [MSSearchDataSource querySearchRecommondDataWithKind:self.kind success:^(NSDictionary * _Nonnull responseInfo) {
        weakSelf.recommondArr = [MSSafeObject ArrayInfo:responseInfo[@"data"]];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
    } failure:^(NSError * _Nonnull error) {
        NSArray *recommondArr = @[@"湘菜", @"⽕fsdfsdfsd火锅", @"⻰fsdfsd龙虾", @"湘菜", @"⽕火锅", @"⻰龙虾", @"湘菜", @"⽕火锅", @"⻰sdfsds龙虾", @"sdfsdf湘菜", @"⽕火fsdgfd锅", @"⻰龙虾"];
        weakSelf.recommondArr = recommondArr;
        [weakSelf.tableView reloadData];
    }];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.historyArr.count > 0;
    }
    return self.recommondArr.count > 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MSSearchDefaultCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MSSearchDefaultCell"];
    cell.textLabel.font = [UIFont systemFontOfSize:13];
    if (indexPath.section == 0) {
        // 历史搜索记录
        [cell refreshSearchDefaultCellWithList:self.historyArr];
    } else {
        // 推荐搜索
        [cell refreshSearchDefaultCellWithList:self.recommondArr];
    }
    _WEAKSELF
    cell.SelectSearchItemBlock = ^(NSString * _Nonnull title) {
        [weakSelf selectItemWithTitle:title];
    };
    
    return cell;;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return [MSSearchDefaultCell caculateSearchDefaultHeight:self.historyArr];
    }
    return [MSSearchDefaultCell caculateSearchDefaultHeight:self.recommondArr];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return (self.historyArr.count > 0)?36.0:0.0;
    }
    return (self.recommondArr.count > 0)?36.0:0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        if (self.historyArr.count < 1) {
            return nil;
        }
    } else {
        if (self.recommondArr.count < 1) {
            return nil;
        }
    }
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, MS_SCREEN_WIDTH, 48.0)];
    headerView.backgroundColor = [UIColor whiteColor];
    // section的头部提示
    UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 16, 200, 20.0)];
    tipLabel.textColor = [UIColor colorWithHexString:@"#444444"];
    tipLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:14];
    tipLabel.textAlignment = NSTextAlignmentLeft;
    tipLabel.text = (section == 0)?@"最近搜索":@"推荐";
    [headerView addSubview:tipLabel];
    
    if (section == 0) {
        [self addClearButtonWithSuperView:headerView];
    }
    return headerView;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

#pragma mark - Event Response

- (void)clearAllHistoryButtonClick:(UIButton *)sender {
    [MSSearchDataSource clearAllLocalSearchList];
    [self loadLocalHistoryData];
}

#pragma mark - Private Method

- (void)addClearButtonWithSuperView:(UIView *)superView {
    // 添加清空按钮
    CGFloat btnRight = 20;
    CGFloat btnWidth = 50;
    CGFloat btnLeft = MS_SCREEN_WIDTH - btnRight - btnWidth;
    UIButton *clearAllBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [clearAllBtn setFrame:CGRectMake(btnLeft, 10, btnWidth, 30)];
    [clearAllBtn setTitle:@"清空" forState:UIControlStateNormal];
    [clearAllBtn setTitleColor:[UIColor colorWithHexString:@"#888888"] forState:UIControlStateNormal];
    [clearAllBtn addTarget:self action:@selector(clearAllHistoryButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    clearAllBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    clearAllBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    //        clearAllBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [superView addSubview:clearAllBtn];
}
/** 选择了某个搜索内容 */
- (void)selectItemWithTitle:(NSString *)title {
    if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(didSelectSearchItem:)]) {
        [self.customDelegate didSelectSearchItem:title];
    }
}

#pragma mark - Getters

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        // 注册cell
        [_tableView registerClass:[MSSearchDefaultCell class] forCellReuseIdentifier:@"MSSearchDefaultCell"];
    }
    return _tableView;
}

#pragma mark -  Memory Method
- (void)dealloc {
    NSLog(@"%s", __func__);
}

@end
